﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.ComponentModel;

namespace Spencen.Mobile.Markup.Extensions
{
    public static class MarkupExtensionExtensions
    {
        public static bool HasNamedProperties( this IMarkupExtension extension, string args )
        {
            return args.Contains( ',' );
        }

        public static IDictionary<string, object> ResolveArgs( this IMarkupExtension extension, string args )
        {
            // TODO: RegEx
            var result = new Dictionary<string, object>();
            var argParts = args.Split( ',' );
            foreach ( var argPart in argParts )
            {
                var pair = argPart.Split( '=' );
                if ( pair.Length == 1 )
                    result.Add( string.Empty, pair[ 0 ].Trim() );
                else
                    result.Add( pair[ 0 ].Trim(), pair[ 1 ].Trim() );
            }
            return result;
        }

        public static void ResolveArgsToProperties( this IMarkupExtension extension, object target, string args )
        {
            var dictionaryOfArgs = ResolveArgs( extension, args );

            foreach ( var pair in dictionaryOfArgs )
            {
                var property = TypeDescriptor.GetProperties( target, true ).Find( pair.Key, false );
                property.SetValue( target, pair.Value );
            }
        }
    }
}
